let username = params.username;
let userpwd = params.userpwd;
let cache_key = 'login_timeouts_' + username;

function _settimeout(){
	let logintimes = cache.get(cache_key);
	if(logintimes.length>=10){
		logintimes.shift();
	}
	logintimes.push((new Date()).getTime());
	cache.set(cache_key,logintimes);
}

function _istimeout(){
	let logintimes = cache.get(cache_key);
	if(!logintimes){
		cache.set(cache_key,[]);
		return 0;
	}
	if(logintimes.length>=3){
		let lasttime = logintimes[logintimes.length-1];
		let now = new Date();
		let len = now.getTime() - lasttime;
		let min15 = 1000 * 60 * 15;
		if(len < min15){
			return len;
		}else{
			return 0;
		}
	}else{
		return 0;
	}
}

if(username && userpwd){
  let timoutms = _istimeout();
	if(timoutms>0){
		ret('用户名密码错误次数太多，请延迟15分钟再试!');
	}else{
    if(username === config.administrator.name &&
      helper.md5(userpwd) === config.administrator.password){
        request.vinculum.session.setUser({username:'root',id:config.administrator.id});
        request.vinculum.session.setUserRoles([]);
        ret(null,'登录成功！');
    }else{
      new service(`${CONST.TABLE_PREFIX}_user_browse_bynameandpwd`).invoke(username,userpwd).then(result=>{
        if(result.length>0){
          let user = result[0];
          request.vinculum.session.setUser(user);
          return new service(`${CONST.TABLE_PREFIX}_user_role_browse_byuserid`).invoke(user.id);
        }else{
          _settimeout();
          ret('用户名或密码错误');
        }
      }).then(result=>{
        let user_roles = [];
        for(let i=0,len=result.length;i<len;i++){
          user_roles.push(result[i].roleid);
        }
        request.vinculum.session.setUserRoles(user_roles);
        ret(null,'登录成功！');
      }).catch(err=>{
        ret(err);
      });
    }
  }
}else{
  ret('请输入用户名或密码');
}
